﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
using System.Diagnostics;

namespace Soket_MMTNC_Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Statistics st = new Statistics();
            st.ShowInTaskbar = false;
            st.ShowDialog();
           
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            Products bu = new Products();
            bu.ShowInTaskbar = false;
            bu.ShowDialog();
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        IPEndPoint ipe;
        public static Socket client;
        Thread connect;
        Product p = new Product();
        Ipserver myip = new Ipserver();
        Thread listenserver;
        public static MainWindow me;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            me = this;
            login lg = new login();
            lg.ShowInTaskbar = false;
            lg.ShowDialog();
        }
        
        public void Run()
        {
            connect = new Thread(connectoserver);
            connect.Start();
            textBox1.ScrollToEnd();
        }
        public string u_p = "";
        public void connectoserver()
        {
            try
            {
                // thiết lập kết nối tới IP của server và port
                ipe = new IPEndPoint(Ipserver.GetIP(), 9999);
                // hiển thị trạng thái lên textbox
                textBox1.Dispatcher.BeginInvoke((Action)(() => { textBox1.AppendText("Kết nối đến server " + Ipserver.GetIP().ToString()); }));
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                client.Connect(ipe);
                //gui thong tin chung thuc den server
                client.Send(myip.MaHoa(u_p));//tai khoan va password
                
                //lay thong tin chung thuc tu ser ver'
              
                byte[] buff = new byte[1024];
                client.Receive(buff);
                int kq = (int)myip.HamGiaiMa(buff);             
                 
                if (kq == 1)
                {
                    listenserver = new Thread(ReceiveFromServer);
                    listenserver.Start(client);
                }
                else
                {
                    if (MessageBox.Show("Thông tin chứng thực không chính xác. Bạn hãy thử lại!\n", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) == MessageBoxResult.OK)
                    {
                        System.Environment.Exit(0);
                        
                    }
                }
            }
            catch (Exception ex)
            {
                if (MessageBox.Show("Xảy ra lỗi khi kết nối đến máy chủ. Bạn hãy thử lại!\n(" + ex.Message + ")", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) == MessageBoxResult.OK)
                {                    
                    System.Environment.Exit(0);
                   
                }
            }
        }
       
        public void ReceiveFromServer(object obj)
        {
            try
            {
                Socket Serversk = (Socket)obj;
                while (true)
                {
                    byte[] buff = new byte[1024 * 5000];
                    Serversk.Receive(buff);
                    DataTable dt = (DataTable)myip.HamGiaiMa(buff);
                    //lay du lieu luu xuong csdl
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        p.UpdatePrice(dt.Rows[i]["id"].ToString(), dt.Rows[i]["price"].ToString());
                    }

                    MessageBox.Show("Quá trình cập nhật giá từ trung tâm quản lí thành công!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
        
                }
            }
            catch (Exception ex)
            {
                if (MessageBox.Show("Kết nối đến máy chủ đã bị ngắt\n(" + ex.Message + ")", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) == MessageBoxResult.OK)
                {
                    System.Environment.Exit(0);
                }
            }
        }
        
        
    }
}
